package main

import (
	"DistributeCalculator/task"
	"context"
	"fmt"
	"google.golang.org/grpc"
	"log"
	"strconv"
	"time"
)

type worker struct {
	workerID int32
}

func (this *worker) connectToPrimary(port string, address string) (task.TaskServiceClient, error) {
	target := address + ":" + port

	conn, err := grpc.Dial(target, grpc.WithInsecure())
	if err != nil {
		log.Printf("端口不可用\n")
		return nil, err
	}
	rpcClient := task.NewTaskServiceClient(conn)
	return rpcClient, nil
}

func (this *worker) callForPullTask(rpcClient task.TaskServiceClient) (*task.ClientRequest, error) {
	for {
		pullTask, err := rpcClient.PullTask(context.Background(), &task.NULL{})
		if err != nil {
			fmt.Println("等待任务中...")
			time.Sleep(time.Second)
			continue
		}
		return pullTask, nil
	}
}

func (this *worker) callForPushResult(rpcClient task.TaskServiceClient, response *task.WorkerResponse) error {
	_, err := rpcClient.PushResult(context.Background(), response)
	if err != nil {
		return err
	}
	return nil
}

func (this *worker) ProcessTask(t *task.ClientRequest) {
	tTask := t.GetTask()
	switch tTask.Operator {
	case "+":
		tTask.Result = strconv.Itoa(int(tTask.Numbers[0] + tTask.Numbers[1]))
		fmt.Println(strconv.Itoa(int(tTask.Numbers[0] + tTask.Numbers[1])))
		break
	default:
		log.Fatalf("invalid operator\n")
	}
}
